package dao;

import java.util.Date;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import entity.PsFunction;

@Repository("functionDao")
public class FunctionDao<K, V> extends HibernateDaoSupport {
	public PsFunction findFunction(PsFunction psFunction) {
		return ((List<PsFunction>)this.getHibernateTemplate().find("from PsFunction where id=?",
				psFunction.getId())).get(0);
	}

	public List<PsFunction> getFunction() {
		return (List<PsFunction>) this.getHibernateTemplate().find(
				"from PsFunction");
	}

	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	public void addUpdateFunction(PsFunction psFunction) throws Exception {
		if (psFunction.getId() != null) {
			PsFunction p = this.getHibernateTemplate().get(PsFunction.class,
					psFunction.getId());
			BeanUtils.copyProperties(psFunction, p);
		} else {
			psFunction.setFunctioncode("0");
			psFunction.setCreationtime(new Date(System.currentTimeMillis()));
			psFunction.setLastupdatetime(new Date(System.currentTimeMillis()));
			this.getHibernateTemplate().save(psFunction);
		}
	}

	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	public void deleteFunction(PsFunction psFunction) throws Exception {
		System.out.println("dao  " + psFunction.getId());
		this.getHibernateTemplate().delete(psFunction);
	}

	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	public void toggleFunction(PsFunction psFunction) throws Exception {
		PsFunction p = this.getHibernateTemplate().get(PsFunction.class,
				psFunction.getId());
		if (p.getIsstart() == 1) {
			p.setIsstart((byte) -1);
		} else {
			p.setIsstart((byte) 1);
		}
	}

}
